package org.west.sky.frame.activiti.study.chapter8;

import de.odysseus.el.util.SimpleContext;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.apache.el.ExpressionFactoryImpl;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * author: chz
 * date: 2024/9/6
 * description: 执行命令
 */
public class RunDemo8_12 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo8_12 runDemo8_3 = new RunDemo8_12();
        runDemo8_3.runDemo();
    }

    private void runDemo() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");

        //准备参数
        Map<String, Object> variables = new HashMap<>();
        Date date = new Date();
        System.out.println("当前时间：" + date);
        String express = "${format.format(date)}";
        variables.put("date", date);
        variables.put("format", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
        Object result = managementService.executeCommand(new ExecuteExpressionCmd(express, variables));
        System.out.println("格式化之后：" + result);
        processEngine.close();
    }

    private class ExecuteExpressionCmd implements Command<Object> {
        /**
         * 表达式
         */
        private String express;
        /**
         * 变量
         */
        private Map<String, Object> variableMap;

        public ExecuteExpressionCmd(String express, Map<String, Object> variableMap) {
            this.express = express;
            this.variableMap = variableMap;
        }

        @Override
        public Object execute(CommandContext commandContext) {
            ExpressionFactory expressionFactory = new ExpressionFactoryImpl();
            SimpleContext simpleContext = new SimpleContext();
            if (variableMap != null) {
                for (Map.Entry<String, Object> entry : variableMap.entrySet()) {
                    if (null != entry.getValue()) {
                        simpleContext.setVariable(entry.getKey(), expressionFactory.createValueExpression(entry.getValue(), entry.getValue().getClass()));
                    } else {
                        simpleContext.setVariable(entry.getKey(), expressionFactory.createValueExpression(null, Object.class));
                    }
                }
            }
            ValueExpression valueExpression = expressionFactory.createValueExpression(simpleContext, express, Object.class);
            return valueExpression.getValue(simpleContext);
        }
    }

}
